package com.summli.basic.class08;

/**
 * 给定一棵二叉树的头节点head，返回这颗二叉树是不是满二叉树
 * 满二叉树定义：L高度，2^L-1
 */
public class Code02_IsFull {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static boolean isFull2(Node head) {
        // 当前的高度，以及所有节点的数量
        if(head == null){
            return true;
        }
        Info result = process(head);
        return (1<<(result.height)) - 1 == result.count;

    }

    private static Info process(Node cur) {
        if(cur == null){
            return new Info(0,0);
        }
        Info leftInfo = process(cur.left);
        Info rightInfo = process(cur.right);
        int height = Math.max(leftInfo.height, rightInfo.height)+1;
        int count = leftInfo.count + rightInfo.count + 1;
        return new Info(height,count);
    }

    public static class Info{
        public int height;
        public int count;

        public Info(int height, int count) {
            this.height = height;
            this.count = count;
        }
    }


    //=============对数器
    public static boolean isFull1(Node head) {
        if (head == null) {
            return true;
        }
        int height = h(head); // 递归求高度
        int nodes = n(head); // 递归求nodes
        return (1 << height) - 1 == nodes;
    }

    public static int h(Node head) {
        if (head == null) {
            return 0;
        }
        return Math.max(h(head.left), h(head.right)) + 1;
    }

    public static int n(Node head) {
        if (head == null) {
            return 0;
        }
        return n(head.left) + n(head.right) + 1;
    }

    // for test
    public static Node generateRandomBST(int maxLevel, int maxValue) {
        return generate(1, maxLevel, maxValue);
    }

    // for test
    public static Node generate(int level, int maxLevel, int maxValue) {
        if (level > maxLevel || Math.random() < 0.5) {
            return null;
        }
        Node head = new Node((int) (Math.random() * maxValue));
        head.left = generate(level + 1, maxLevel, maxValue);
        head.right = generate(level + 1, maxLevel, maxValue);
        return head;
    }

    public static void main(String[] args) {
        int maxLevel = 5;
        int maxValue = 100;
        int testTimes = 1000000;
        for (int i = 0; i < testTimes; i++) {
            Node head = generateRandomBST(maxLevel, maxValue);
            if (isFull1(head) != isFull2(head)) {
                System.out.println("Oops!");
            }
        }
        System.out.println("finish!");
    }
}
